from django.http import HttpResponseNotFound
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.core.paginator import Paginator, InvalidPage, EmptyPage

from shop.models import Order


@login_required
def show_orders(request):
    """ List all orders """

    orders = Order.objects.filter(
        user=request.user,
    ).order_by('-created')

    paging = Paginator(orders, 20)

    # defaults to page 1 if page is invalid
    try:
        page = int(request.GET['page'])
    except (KeyError, ValueError):
        page = 1

    # loads requested page, defaults to page 1 on on invalid page number
    try:
        orders_page = paging.page(page)
    except (EmptyPage, InvalidPage):
        orders_page = paging.page(1)

    output = {
         'orders': orders_page,
     }

    return render_to_response(
        'orders.html',
        output,
        context_instance=RequestContext(request)
    )


@login_required
def show_completed_order(request, order_id):
    """Loads a payed or delivered order for user by Order.id"""
    try:
        order = Order.objects.get(
            user=request.user,
            id=order_id,
            status__in=('P', 'D')
        )
        return render_to_response(
            'order.html',
            {'order': order},
            context_instance=RequestContext(request)
        )
    except Order.DoesNotExist:
        return HttpResponseNotFound